<?php
/**
 * Created by PhpStorm.
 * User: duanyuhan
 * Date: 2020/4/26
 * Time: 13:55
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\User;
use App\Org\code\Code;
use Illuminate\Http\Request;
use Illuminate\Queue\RedisQueue;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
Use App\Model\Role;


class LoginController extends Controller
{

    public function login()
    {
        //后台登录页
        return view('admin.login');
    }

    //验证码
    public function code()
    {
        $code = new Code();
        return $code->make();
    }

    public function doLogin(Request $request)
    {
        //接受表单提交数据
        $input = $request->except('_token');


        //进行表单验证
//        $validate = Validator::make('验证数据','验证规则','错误提示信息');
        //验证规则
        $rule = [
            'username'=>'required||between:3,18',
            'password'=>'required||alpha_dash',
        ];
        //错误信息
        $msg = [
            'username.required'=>'用户名必须输入!',
            'username.between'=>'用户名为3-18位!',

            'password.required'=>'密码必须输入!',
            'password.alpha_dash'=>'密码为数字字母下划线!',

        ];
        $validate = Validator::make($input,$rule,$msg);

        if($validate->fails()){
            return redirect('admin/login')
                ->withErrors($validate)
                ->withInput();
        }


        //2.验证码验真
        if(strtolower($input['code']) != strtolower(session()->get('code'))){
            return redirect('/admin/login')->with('errors','验证码不正确');
        }
        //3.验证是否有此用户(用户名,密码,验证码   )
        $member = User::where('user_name',$input['username'])->first();

        if(!$member){
            return redirect('/admin/login')->with('errors','用户名不存在');
        }

        if($input['password'] != Crypt::decrypt($member->user_pass)){
            return redirect('/admin/login')->with('errors','密码不正确');
        }
        //4.保存用户信息以及权限到session中
        //获取当前用户的角色
        $role = $member->role;
        $per = [];
        foreach ( $role as $v){
            $perms = $v->permission;
            foreach($perms as $perm){
                $per[] = $perm->per_url;
            }
        }

        //存入角色ID
        $role = $member->role;
        foreach($role as $v){
            if($v->id == 1){
                session()->put('superAdmin','1');
            }
        }
        //权限去重
        $per = array_unique($per);
        session()->put(['user'=>$member,'per'=>$per]);

        //5.跳转到首页

        return redirect('admin/index');

    }

    //后台首页
    public function index()
    {
        return view('admin.index');
    }

    //后台欢迎页
    public function welcome()
    {
        return view('admin.welcome');
    }

    //退出登录
    public function logout()
    {
        //清空sessioo用户信息
        session()->flush();
        //退到登录页
        return redirect('admin/login');
    }

    public function noAccess()
    {
        return view('error.noaccess');
    }
}